package com.easylinkin.linkappapi.security.controller;

import com.easylinkin.linkappapi.annotation.CommonOperateLogAnnotate;
import com.easylinkin.linkappapi.operatelog.LogHelper;
import com.easylinkin.linkappapi.operatelog.constant.LogConstant.LogModule;
import com.easylinkin.linkappapi.operatelog.constant.LogConstant.LogOperateType;
import java.util.List;

import javax.annotation.Resource;

import com.easylinkin.linkappapi.security.entity.LinkappUser;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappRole;
import com.easylinkin.linkappapi.security.entity.RoleRefSpaceDTO;
import com.easylinkin.linkappapi.security.entity.RoleRefUserDTO;
import com.easylinkin.linkappapi.security.service.LinkappRoleService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import site.morn.boot.data.DisplayableControllerSupport;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;
import site.morn.rest.RestModel;

/**
 * 角色控制器
 *
 * @author liuming
 */
@Api(tags = "角色管理")
@RestController
@RequestMapping("/linkappRole")
public class LinkappRoleController extends DisplayableControllerSupport<LinkappRole, Long, LinkappRoleService> {

	
	@Resource
	LinkappUserContextProducer linkappUserContextProducer;
	/**
	 * 新增
	 */
	@Override
    @ApiOperation("新增")
	@CommonOperateLogAnnotate(module = LogModule.ROLE, desc = "")
	@PostMapping("/add")
	public RestMessage add(@RequestBody RestModel<LinkappRole> restModel) {
		String tenatnId = linkappUserContextProducer.getCurrent().getTenantId();
		LinkappRole linkappRole = restModel.getModel();
		linkappRole.setTenantId(tenatnId);
		LogHelper.setContent(LogOperateType.ROLE_ADD,linkappRole.getName());
		return super.add(restModel);
	}

	/**
	 * 修改
	 */
	@ApiOperation("修改")
	@CommonOperateLogAnnotate(module = LogModule.ROLE, desc = "")
	@PutMapping("/update")
	@Override
	public RestMessage update(@RequestBody RestModel<LinkappRole> restModel) {
		LinkappRole linkappRole = restModel.getModel();
		LinkappRole old = service().findByRoleId(linkappRole.getId());
		LogHelper.setContent(LogOperateType.ROLE_UPDATE,old.getName());
		return super.update(restModel);
	}
	
	/**
	 * 删除
	 */
	@Override
    @ApiOperation("删除")
	@CommonOperateLogAnnotate(module = LogModule.ROLE, desc = "")
	@PutMapping("delete/{roleId}")
	public RestMessage delete(@PathVariable Long roleId) {
		LinkappRole old = service().findByRoleId(roleId);
		LogHelper.setContent(LogOperateType.ROLE_DELETE,old.getName());
		service().delete(roleId);
		return RestBuilders.successMessage();
	}

	@ApiOperation(value = "根据用户Id查询用户")
	@ApiImplicitParam(name = "userId", value = "用户Id", required = true)
	@GetMapping("getRolesByUserId/{userId}")
	public RestMessage getRolesByUserId(@PathVariable Long userId) {
		return RestBuilders.successMessage(service().getByUserId(userId));
	}

	@ApiOperation(value = "查询当前用户可见的角色列表")
	@GetMapping("searchAll")
	public RestMessage getRolesForCurrentTenant() {
		//20220821bug 1013039 用户授权的时候，可以看到非本项目的角色修改，增加租户隔离(本来统一拦截有处理，这里增加逻辑改为明传)
		LinkappRole role = new LinkappRole();
		LinkappUser linkappUser = linkappUserContextProducer.getNotNullCurrent();
		role.setTenantId(linkappUser.getTenantId());
		return RestBuilders.successMessage(service().findRoles(role));
	}

	@ApiOperation(value = "分页-查询当前用户可见的角色列表")
	@PostMapping("/selectPage")
	public RestMessage selectPage(@RequestBody RequestModel<LinkappRole> requestModel) {
        Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
        Assert.notNull(requestModel.getPage(), "page 不能为空");
        IPage<LinkappRole> record = service().selectPage(requestModel.getPage(), requestModel.getCustomQueryParams());
        return RestBuilders.successBuilder().data(record).build();
    }

	@ApiOperation(value = "根据角色ID获取所关联空间集合")
	@GetMapping("/selectSpaceByRole/{roleId}")
	public RestMessage selectSpaceByRole(@PathVariable Long roleId) {
		return RestBuilders.successBuilder().data(service().selectSpaceByRole(roleId)).build();
	}

	@ApiOperation(value = "修改、新增角色-空间关联")
	@PostMapping("/role2Spaces")
    public RestMessage role2Spaces(@RequestBody RoleRefSpaceDTO roleRefSpaceDTO) {
    	service().role2Spaces(roleRefSpaceDTO.getRole(), roleRefSpaceDTO.getSpaces());
        return RestBuilders.successMessage();
    }

	@ApiOperation(value = "根据角色ID获取所关联的用户集合")
	@GetMapping("/selectUserByRole/{roleId}")
	public RestMessage selectUserByRole(@PathVariable Long roleId) {
		return RestBuilders.successBuilder().data(service().selectUserByRole(roleId)).build();
	}

	@ApiOperation(value = "修改、新增角色-用户关联")
	@PostMapping("/role2Users")
    public RestMessage role2Users(@RequestBody RoleRefUserDTO roleRefUserDTO) {
    	service().role2Users(roleRefUserDTO.getRole(), roleRefUserDTO.getUsers());
        return RestBuilders.successMessage();
    }

	/**
	 * 返回的message信息描述好像不太形象
	 * @param code
	 * @return
	 */
	@ApiOperation(value = "角色编码唯一性校验")
	@RequestMapping("/checkRole/{code}")
    public RestMessage checkRole(@PathVariable String code) {
    	String tenantId = linkappUserContextProducer.getCurrent().getTenantId();
    	LinkappRole role = new LinkappRole();
    	role.setTenantId(tenantId);
    	role.setCode(code);
    	List<LinkappRole> roles = service().checkRole(role);
    	if(roles.isEmpty()) {
    		return RestBuilders.successBuilder().message("角色编码为空").build();
    	}else {
    		return RestBuilders.failureBuilder().message("角色编码不为空").build();
    	}
    }

}


